/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#ifndef MK_TCP_SERVER_H
#define MK_TCP_SERVER_H
#include "MkSocket/MkSocket.h"
#include "MkUtil/MkThread.h"
#include "MkUtil/MkRwLock.h"

class CMkTcpSession;
class CMkEventPool;
class CMkEvent;
class CMkTimer;
typedef MkMap<Uint64, CMkTcpSession*> MapTcpSession;
class MkApi CMkTcpServer : public CMkSocket
{
public:
    CMkTcpServer(CMkEventPool* pEventPool, CMkTimer* pTimer, Uint32 MaxConnections);
    virtual ~CMkTcpServer();

    virtual Uint32 StartServer(Uint16 Port, const MkString& Ip = "");
    virtual Uint32 StopServer();
    void SetMaxConnections(Uint32 MaxConnections) { m_MaxConnections = MaxConnections; }
    void CheckSession();
    CMkEventPool* GetEventPool() { return m_EventPool; }
    CMkTimer* GetTimer() { return m_pTimer; }

    virtual CMkTcpSession* CreateNewSession(CMkEvent *pEvent, CMkTimer* pTimer) = 0;
    virtual Uint32 OnSessionAccepted(CMkTcpSession *pSession);
    virtual Uint32 OnSessionEventRemoved(CMkTcpSession* pSession);
    //virtual Uint32 Send(const Uint64& SessionId, const CMkBufferList& BufferList);
    virtual Uint32 CloseSession(const Uint64& SessionId);
    virtual CMkTcpSession* GetTcpSession(const Uint64& SessionId);
protected:
    virtual Uint32 OnAccept() override;
protected:
    CMkRwLock                           m_SessionLock;
    MapTcpSession                       m_MapTcpSession;
private:
    CMkEventPool                        *m_EventPool;
    CMkTimer                            *m_pTimer;
    MkString                            m_CheckTimer;
    Uint32                              m_MaxConnections;
};

#endif
